package com.gjy.util.basic;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.gjy.util.reflect.ObjectUtil;
import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-12-05 15:08:09
 */
public class TreeHelpUtil {

    public static <T> List<Tree<Long>> listWithTree(List<T> t) {
        if (!CollectionUtils.isEmpty(t)) {
            List<TreeNode<Long>> collect = t.stream()
                    .map(TreeHelpUtil::getLongTreeNode)
                    .collect(Collectors.toList());

            return TreeUtil.build(collect, 0L);
        }
        return Collections.emptyList();
    }

    private static <T> TreeNode<Long> getLongTreeNode(T t) {
        TreeNode<Long> node = new TreeNode<>();
        node.setId(((Long) ObjectUtil.get(t, "id")));
        node.setParentId(((Long) ObjectUtil.get(t, "parentId")));
        node.setName(((String) ObjectUtil.get(t, "name")));
        node.setWeight(((Long) ObjectUtil.get(t, "weight")));
        HashMap<String, Object> extra = Maps.newHashMap();
        extra.put("a1",ObjectUtil.get(t, "a1"));
        extra.put("a2",ObjectUtil.get(t, "a2"));
        extra.put("a3",ObjectUtil.get(t, "a3"));
        node.setExtra(extra);
        return node;
    }
}
